package pers.uang.crud.controller;

import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import pers.uang.crud.pojo.Department;
import pers.uang.crud.pojo.Employee;
import pers.uang.crud.service.EmployeeService;

import java.util.List;


@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    // 分页查询员工信息
    @GetMapping(value = {"", "/{pageNum}"})
    public String getAllEmpByPage(@PathVariable(value = "pageNum", required = false) Integer pageNum, Model model){
        if (pageNum == null || pageNum <= 0){
            pageNum = 1;
        }
        PageInfo<Employee> pageInfo = employeeService.getAllEmpByPage(pageNum);
        if (pageNum > pageInfo.getPages()){
            pageInfo = employeeService.getAllEmpByPage(pageInfo.getPages());
        }
        model.addAttribute("pageInfo", pageInfo);
        return "index";
    }

    // 添加用户信息
    @PostMapping
    public String addEmployee(Employee employee, Integer deptId, String pageNum) {
        adjustEmp(employee, deptId);
        employeeService.addEmployee(employee);
        return "redirect:/employee/" + ((pageNum == null) ? "" : pageNum);
    }

    // 修改用户信息
    @GetMapping("/to/update/{empId}")
    @ResponseBody
    public Employee toUpdate(@PathVariable("empId") Integer empId) {
        return employeeService.getEmployeeById(empId);
    }

    // 更新信息
    @PutMapping
    public String updateEmployee(Employee employee, Integer deptId, String pageNum) {
        adjustEmp(employee, deptId);
        employeeService.updateEmployee(employee);
        return "redirect:/employee/" + ((pageNum == null) ? "" : pageNum);
    }


    // 删除用户信息
    @DeleteMapping("/{empId}")
    public String deleteEmployee(@PathVariable("empId") Integer empId, String pageNum) {
        employeeService.deleteEmployeeById(empId);
        return "redirect:/employee/" + ((pageNum == null) ? "" : pageNum);
    }

    // 批量删除用户
    @DeleteMapping
    public String deleteEmployee(String empItem, String pageNum) {
        employeeService.batchDelEmp(empItem);
        return "redirect:/employee/" + ((pageNum == null) ? "" : pageNum);
    }


    private void adjustEmp(Employee emp, Integer deptId) {
        String gender = emp.getGender();
        emp.setGender("M".equals(gender) ? "男" : "女");

        Department dept = new Department();
        dept.setDeptId(deptId);
        emp.setDept(dept);
    }

}
